#!/sbin/sh
#
# Copyright 2010 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# Copyright 2016 Hans Rosenfeld <rosenfeld@grumpf.hope-2000.org>
#

. /lib/svc/share/ipf_include.sh
. /lib/svc/share/smf_include.sh

SSHDIR=/etc/ssh
KEYGEN="/usr/bin/ssh-keygen -q"
PIDFILE=/var/run/sshd.pid

# Checks to see if RSA, and DSA host keys are available
# if any of these keys are not present, the respective keys are created.
create_key()
{
	keypath=$1
	keytype=$2

	if [ ! -f $keypath ]; then
		# 
		# HostKey keywords in sshd_config may be preceded or
		# followed by a mix of any number of space or tabs,
		# and optionally have an = between keyword and
		# argument.  We use two grep invocations such that we
		# can match HostKey case insensitively but still have
		# the case of the path name be significant, keeping
		# the pattern somewhat more readable.
		#
		# The character classes below contain one literal
		# space and one literal tab.
		#
		grep -i "^[ 	]*HostKey[ 	]*=\{0,1\}[ 	]*$keypath" \
		    $SSHDIR/sshd_config | grep "$keypath" > /dev/null 2>&1

		if [ $? -eq 0 ]; then
			echo Creating new $keytype public/private host key pair
			$KEYGEN -f $keypath -t $keytype -N ''
			if [ $? -ne 0 ]; then
				echo "Could not create $keytype key: $keypath"
				exit $SMF_EXIT_ERR_CONFIG
			fi
		fi
	fi
}

create_ipf_rules()
{
	FMRI=$1
	ipf_file=`fmri_to_file ${FMRI} $IPF_SUFFIX`
	ipf6_file=`fmri_to_file ${FMRI} $IPF6_SUFFIX`
	policy=`get_policy ${FMRI}`

	#
	# Get port from /etc/ssh/sshd_config
	#
	tports=`grep "^Port" /etc/ssh/sshd_config 2>/dev/null | \
	    awk '{print $2}'`

	echo "# $FMRI" >$ipf_file
	echo "# $FMRI" >$ipf6_file
	for port in $tports; do
		generate_rules $FMRI $policy "tcp" $port $ipf_file
		generate_rules $FMRI $policy "tcp" $port $ipf6_file _6
	done
}

# This script is being used for two purposes: as part of an SMF
# start/stop/refresh method, and as a sysidconfig(8)/sys-unconfig(8)
# application.
#
# Both, the SMF methods and sysidconfig/sys-unconfig use different
# arguments..

case $1 in 
	# sysidconfig/sys-unconfig arguments (-c and -u)
'-c')
	/usr/bin/ssh-keygen -A
	if [ $? -ne 0 ]; then
		create_key $SSHDIR/ssh_host_rsa_key rsa
		create_key $SSHDIR/ssh_host_dsa_key dsa
	fi
	;;

'-u')
	# sys-unconfig(8) knows how to remove ssh host keys, so there's
	# nothing to do here.
	:
	;;

	# SMF arguments (start and restart [really "refresh"])

'ipfilter')
	create_ipf_rules $2
	;;

'start')
	#
	# If host keys don't exist when the service is started, create
	# them; sysidconfig is not run in every situation (such as on
	# the install media).
	# 
	/usr/bin/ssh-keygen -A
	if [ $? -ne 0 ]; then
		create_key $SSHDIR/ssh_host_rsa_key rsa
		create_key $SSHDIR/ssh_host_dsa_key dsa
	fi

	/usr/lib/ssh/sshd
	;;

'restart')
	if [ -f "$PIDFILE" ]; then
		/usr/bin/kill -HUP `/usr/bin/cat $PIDFILE`
	fi
	;;

*)
	echo "Usage: $0 { start | restart }"
	exit 1
	;;
esac	

exit $?
